package com.telra.app.server2.jms;

import com.telra.app.server2.config.MQConfig;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Log4JLogger;

import javax.jms.*;

/**
 * Simulates order traffic by randomly creating orders and publishing them on JMS.
 * Can be throttled to increase/decrease rate to testing load.
 */
public class JMSPublisherService {

    private static final Log4JLogger log = (Log4JLogger) LogFactory.getFactory().getInstance(JMSPublisherService.class);
    private MQConfig config;

    public JMSPublisherService() {
        //empty
    }

    public void setConfig(MQConfig config) {
        this.config = config;
        init();
    }
    
    private void init() {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(config.getMqUrl());
        connectionFactory.setUseAsyncSend(true);
        try {
            Connection connection = connectionFactory.createConnection();
            connection.start();

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            Topic topic = session.createTopic(config.getMqTopic());
            MessageProducer producer = session.createProducer(topic);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            log.info("started publisher");


        }
        catch (JMSException e) {
            log.error(e);
        }

    }
}

